#-------------------------------------------------------------------------------
# Name:        csv_to_kml
# Purpose:     Reads a csv file descibing a set of wind turbine locations
#              and create a CSV file representing all of the locations
#              grouped by country, offshore vs onshore, and then windfarm.
#              Can create one placemark per wind farm, or one group per turbine
#
# Issues:      Won't work with non-ascii unicode characters
#              Skips missing latitudes or longitudes for turbines
#
# Author:      sam.hawkins@vattenfall.com
#
# Created:     17/01/2012
# Copyright:   (c) slha 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import csv
from simplekml import Kml
import numpy as np

infile  = 'turbine_locations.csv'
outfile = r'C:\scratch\parks.kml'


def main():
    create_park_file(infile,outfile)
    #create_turbine_kml_set(infile,outfile)

def create_park_file(infile, outfile):
    kml       = Kml()
    countries = {}
    parks     = {}

    csvreader = csv.DictReader(open(infile))
    for row in csvreader:
        country = row['Country']
        park    = row['Park']
        lat     = row['Latitude']
        lon     = row['Longitude']

        if lat=='nan' or lon=='nan':
            print 'skipping %s' % park
            continue

        #
        # Check whether entry exists
        #
        if country not in countries:
            cfolder            = kml.newfolder(name=country)
            countries[country] = cfolder
        #
        # Can be sure country exists now
        #
        cfolder = countries[country]
        if park not in parks:
            pfolder            = cfolder.newfolder(name=park)
            parks[park]        = pfolder

        pfolder =parks[park]
        ppmark  = pfolder.newpoint(name=park, coords=[(lon, lat)])

    kml.save(outfile)


def create_turbine_kml_set(infile,outfile):
    #
    # Read csv file into a record array
    #
    recs      = np.genfromtxt(infile, delimiter=',', names=True, dtype=None)
    print recs.dtype

    #
    # Get a unique set of country and park names
    #
    countries = set(recs['Country'])
    parks     = set(recs['Park'])
    turbines  = set(recs['Turbine'])

    #
    # Create a new document
    #
    kml = Kml()
    for country in countries:
        cfolder = kml.newfolder(name=country)
        for park in parks:
            pfolder = cfolder.newfolder(name=park)
            for turbine in recs[recs['Park']==park]:
                lon = turbine['Latitude']
                lat = turbine['Latitude']
                if np.isnan(lat) or np.isnan(lon):
                    continue
                else:
                    tpmark  = pfolder.newpoint(name=turbine, coords=[(lon, lat)])

    kml.save(outfile)


def create_turbine_kml(infile, outfile):
    kml       = Kml()
    countries = {}
    parks     = {}
    turbines  = {}

    csvreader = csv.DictReader(open(infile))
    for row in csvreader:
        country = row['Country']
        park    = row['Park']
        turbine = row['Turbine']
        lat     = row['Latitude']
        lon     = row['Longitude']

        #
        # Check whether entry exists
        #
        if country not in countries:
            cfolder            = kml.newfolder(name=country)
            countries[country] = cfolder
        #
        # Can be sure country exists now
        #
        cfolder = countries[country]
        if park not in parks:
            pfolder            = cfolder.newfolder(name=park)
            parks[park]        = pfolder

        #
        # Can be sure both country and park exist now
        #
        pfolder = parks[park]
        if turbine not in turbines:
            tpmark  = pfolder.newpoint(name=turbine, coords=[(lon, lat)])
    kml.save(outfile)

if __name__ == '__main__':
    main()
